package com.gofaraway.service.enumfacade;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.gofaraway.common.domin.Response;
import com.gofaraway.common.exception.v2.BusinessException;
import com.gofaraway.service.enumfacade.strategy.EnumStrategy;
import com.gofaraway.service.facade.request.EnumQueryRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static com.gofaraway.common.exception.v2.CommonErrorConstants.BIZ_OPERATE_FORBIDDEN;
import static com.gofaraway.common.exception.v2.CommonErrorConstants.BIZ_STATUS_EMPTY_RESULT;

/**
 * @author ChenPeng
 * @Date 2024/4/12 14:58
 */
@Component
@Slf4j
public class EnumContext implements ApplicationContextAware {


    private final Map<String, EnumStrategy> strategyMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        Map<String, EnumStrategy> beansOfType = applicationContext.getBeansOfType(EnumStrategy.class);

        if (CollectionUtils.isEmpty(beansOfType)) {
            log.warn("EnumContext beansOfTypeMap is null");
            return;
        }

        for (EnumStrategy enumStrategy : beansOfType.values()) {
            strategyMap.put(enumStrategy.enumType(), enumStrategy);
        }
        log.info("init enumStrategyMap end,strategyMap size is [{}]", strategyMap.size());
    }

    public Response<Object> executeStrategy(EnumQueryRequest request) {
        EnumStrategy strategy = strategyMap.get(request.getEnumType());
        if (strategy == null) {
            throw BusinessException.of(BIZ_STATUS_EMPTY_RESULT).withPlaceHolderParam("：未知的枚举编码");
        }

        return Response.success(strategy.getEnumResultByCondition());
    }
}
